<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片区域 -->
        <el-card class="box-card">
            <!-- 搜索区域 -->
            <el-row :gutter="20">
                <el-col :span="8">
                     <!-- 搜索框 -->
                    <el-input placeholder="请输入搜索内容" v-model="queryinfo.query" clearable @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="adddialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>
            <!-- 表格区域 -->
            <el-table :data="userlist" stripe border>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="姓名" prop="username"></el-table-column>
                <el-table-column label="电话" prop="mobile"></el-table-column>
                <el-table-column label="邮箱" prop="email"></el-table-column>
                <el-table-column label="角色" prop="role_name"></el-table-column>
                <el-table-column label="状态" >
                    <!-- 作用于插槽 -->
                    <template slot-scope="scope">
                        <!-- scope可以获取到当前行的数据 -->
                        <el-switch v-model="scope.row.mg_state" @change="Switchchanged(scope.row)">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180px">
                    <template slot-scope="scope">
                        <!-- 修改按钮 -->
                        <el-button type="primary" icon="el-icon-edit"  @click="editDailog(scope.row.id)" size="mini"></el-button>
                        <!-- 删除按钮 -->
                        <el-button type="danger" icon="el-icon-delete" @click="removeUser(scope.row.id)" size="mini"></el-button>
                       <!-- 分配角色按钮 -->
                           <el-tooltip  effect="dark" content="分配角色" placement="top" :enterable="false">
                                 <el-button @click="setRole(scope.row)" type="warning" icon="el-icon-setting" size="mini"></el-button>
                            </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页区域 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="queryinfo.pagenum" :page-sizes="[1, 2, 5, 10]"
            :page-size="queryinfo.pagesize" layout="total, sizes, prev, pager, next, jumper"
            :total="total">
        </el-pagination>
        </el-card>
        <!-- 添加用户弹出框 -->
        <el-dialog title="添加用户" :visible.sync="adddialogVisible"
         width="30%" @close="addDialogClosed">
            <!-- 内容区域 -->
            <el-form :model="addForm" :rules="addFormrules" ref="addFormRef" label-width="100px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="addForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="addForm.password" type="password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="addForm.email"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="mobile">
                <el-input v-model="addForm.mobile"></el-input>
            </el-form-item>
            </el-form>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
            <el-button @click="adddialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改弹出框 -->
        <el-dialog title="修改用户" :visible.sync="EditdialogVisible" width="30%" @close="editDailogClosed">
            <el-form :model="editForm" :rules="editFormrules" ref="editFormRef" label-width="70px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="editForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email" ></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="mobile">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="EditdialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editUserInfo(editForm.id)">确 定</el-button>
        </span>
        </el-dialog>
        <!-- 分配角色弹出框 -->
        <el-dialog title="分配角色" :visible.sync="roleVisible" width="30%" @close="closedRole">
        <p>当前的用户：{{userinfo.username}}</p>
        <p>当前的角色：{{userinfo.role_name}}</p>
        <p>分配新角色：
            <el-select v-model="selectedRole" placeholder="请选择">
            <el-option v-for="item in rolelist" :key="item.id"
            :label="item.roleName"
            :value="item.id">
            </el-option>
  </el-select>
        </p>
        <span slot="footer" class="dialog-footer">
            <el-button @click="roleVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitrole">确 定</el-button>
        </span>
        </el-dialog>

    </div>
</template>

<script>
export default {
    data(){
        //自定义邮箱验证规则
        var checkEmail =(rule,value,cb)=>{
            const regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
            if(regEmail.test(value)){
                return cb();
            }
            cb(new Error('请输入合法的邮箱地址'))
        }
        //自定义手机验证规则
        var checkMobile = (rule,value,cb)=>{
            const regMobile = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;
            if(regMobile.test(value)){
                cb();
            }
            cb(new Error('请输入合法的手机号码'))
        }
        return{
            //查询用户数据参数
            queryinfo:{
                query:'',
                //当前页码数
                pagenum:1,
                //每页显示的数量
                pagesize:2
            },
            userlist:[],
            total:0,
            //添加用户框的展示与隐藏
            adddialogVisible:false,
            //修改用户框的展示与隐藏
            EditdialogVisible:false,
            //添加用户集合
            addForm:{
                username:'',
                password:'',
                email:'',
                mobile:''
            },
            //根据id获取到的用户信息
            editForm:{},
            //添加用户规则
            addFormrules:{
                username:[
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }    
                ],
                password:[
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }    
                ],
                email:[
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator:checkEmail, trigger: 'blur' }    
                ],
                mobile:[
                    { required: true, message: '请输入手机号码', trigger: 'blur' },
                    {  validator: checkMobile,  trigger: 'blur' }    
                ]                
            },
            //修改用户规则
            editFormrules:{
                email:[
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator:checkEmail, trigger: 'blur' }    
                ],
                mobile:[
                    { required: true, message: '请输入手机号码', trigger: 'blur' },
                    {  validator: checkMobile,  trigger: 'blur' }    
                ]          
            },
            //分配角色对话框的显示与隐藏
            roleVisible: false,
            //角色的信息
            userinfo:{},
            //所有的角色列表
            rolelist:[],
            //选择的角色
            selectedRole:''
        }
    },
    created(){
        this.getUserList();
    },
    methods:{
        async getUserList(){
           const {data:res} = await this.$http.get('users',{params:this.queryinfo})
            if(res.meta.status!==200){
                return this.$message.error('获取用户列表数据失败')
            }
            this.userlist = res.data.users;
            this.total = res.data.total;
            //console.log(res);
        },
        //改变每页显示的数量
        handleSizeChange(newsize){
            this.queryinfo.pagesize = newsize;
            this.getUserList();
        },
        //改变页码
        handleCurrentChange(newpage){
            this.queryinfo.pagenum = newpage;
            this.getUserList();
        },
        //状态改变
        async Switchchanged(userinfo){
            const {data:res} = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
            if(res.meta.status!=200){
                userinfo.mg_state = ! userinfo.mg_state;
                return this.$message.error('更改用户状态失败');
            }
            this.$message.success('更新用户状态成功')
       },
       //弹框关闭后请清空表单内容
       addDialogClosed(){
           this.$refs.addFormRef.resetFields();
       },
       //点击确定，添加新用户
       addUser(){
           this.$refs.addFormRef.validate(async valid=>{
               if(!valid) return;
            const {data:res} =await this.$http.post('users',this.addForm);
            if(res.meta.status!=201) return this.$message.error(res.meta.msg);
            this.$message.success('添加用户成功');
            //关闭弹框
            this.adddialogVisible = false;
            //重新获取页面数据
            this.getUserList();
           })
       },
       //修改操作
       async editDailog(id){
           const {data:res} = await this.$http.get('users/'+id);
           if(res.meta.status!=200) return this.$message.error('查询用户信息失败');
            this.editForm = res.data;
           // console.log(this.editForm)
           this.EditdialogVisible = true;
       },
       //修改框关闭后清空表单
       editDailogClosed(){
           this.$refs.editFormRef.resetFields();
       },
       //实现用户信息的修改
       editUserInfo(id){
           this.$refs.editFormRef.validate(async valid=>{
               if(!valid) return this.$message.error('输入的信息不合法');
                const {data:res} = await this.$http.put('users/'+id,{
                    email:this.editForm.email,
                    mobile:this.editForm.mobile
                })
                if(res.meta.status!=200) return this.$message.error('修改用户信息失败');
                this.$message.success('用户信息修改成功');
                this.EditdialogVisible = false;
                this.getUserList();
           })
           
       },
       //实现用户信息的删除
       async removeUser(id){
         const confirmresult =await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        //返回值cancel代表取消，confirm代表确定
        if(confirmresult=='cancel')
        return this.$message.info('已取消删除');

        const {data:res} = await this.$http.delete('users/'+id);
        if(res.meta.status!=200) return this.$message.error('删除失败');
        this.$message.success('删除成功');
        this.getUserList();
       },
       //显示角色修改对话框
       async setRole(userinfo){
           this.userinfo = userinfo;
            //获取所有的角色列表
            const {data:res} = await this.$http.get('roles');
            if(res.meta.status!=200){
                return this.$message.error('获取角色列表失败');
            }
            this.rolelist = res.data;
           this.roleVisible = true;
       },
       //实现修改功能
       async submitrole(){
           if(!this.selectedRole){
               return this.$message.info('请选择角色');
           }
           const {data:res} = await this.$http.put(`users/${this.userinfo.id}/role`,{
               rid:this.selectedRole
           })
           if(res.meta.status!=200){
               return this.$message.error('分配角色失败');
           }
             this.$message.success('分配角色成功');
             this.getUserList();
             this.roleVisible = false;
       },
        //关闭弹框后清空用户信息
       closedRole(){
           this.userinfo = {},
           this.selectedRole =''
       }
}
}
</script>

<style lang="less" scoped>

</style>